package controller

import (
	"gitee.com/song-yao-shun/MQH/model"
	"gitee.com/song-yao-shun/MQH/response"
	"gitee.com/song-yao-shun/MQH/respository"
	"gitee.com/song-yao-shun/MQH/vo"
	"github.com/gin-gonic/gin"
	"log"
	"strconv"
)

type ITsController interface {
	RestController
}

type TsController struct {
	TsRty respository.TsRepository
}

func (t TsController) Create(ctx *gin.Context) {
	// 接收参数
	var voRequest vo.CreateTsRequest
	if err := ctx.ShouldBind(&voRequest); err != nil {
		response.Fail(ctx, nil, "数据验证错误！")
		return
	}

	// 创建 page
	result := model.Ts{
		SceneId: 	voRequest.SceneId,
		FctId: 		voRequest.FctId,
		Name: 		voRequest.Name,
	}

	resultId, err := t.TsRty.Create(result)
	if err != nil {
		response.Fail(ctx, nil, "新建失败！")
		return
	}

	// 返回
	response.Success(ctx, gin.H{"data":resultId}, "新建成功！")
}

func (t TsController) Update(ctx *gin.Context) {
	// 接收参数
	var voRequest vo.CreateTsRequest
	if err := ctx.ShouldBind(&voRequest); err != nil {
		response.Fail(ctx, nil, "数据验证错误，请检查提交的内容！")
		return
	}

	// 获取 path 中的参数
	pathId, _ := strconv.Atoi(ctx.Params.ByName("id"))
	updateResult, err := t.TsRty.SelectById(int64(pathId))
	if err != nil {
		response.Fail(ctx, nil, "测试步骤不存在！")
		return
	}

	// 更新 struct
	updateResult.SceneId 	= voRequest.SceneId
	updateResult.FctId 		= voRequest.FctId
	updateResult.Name 		= voRequest.Name

	log.Println(updateResult,*updateResult)

	result, err := t.TsRty.Update(*updateResult)
	if err != nil {
		panic(err)
	}

	response.Success(ctx, gin.H{"data":result}, "修改成功。")
}

func (t TsController) Show(ctx *gin.Context) {

	// 获取 path 中的参数
	pathId, _ := strconv.Atoi(ctx.Params.ByName("id"))
	result, err := t.TsRty.SelectById(int64(pathId))
	if err != nil {
		response.Fail(ctx, nil, "测试步骤不存在！")
		return
	}

	response.Success(ctx, gin.H{"data":result}, "")
}

func (t TsController) Delete(ctx *gin.Context) {

	// 获取 path 中的参数
	pathId, _ := strconv.Atoi(ctx.Params.ByName("id"))

	//// 判断存在测试用例，不允许删除
	//// 接收参数
	//var voList vo.SceneList
	//voList.SceneId = int64(pathId)
	//_, total := s.SceneRty.List(voList)
	//if total > 0 {
	//	response.Fail(ctx, nil, "存在子场景，不允许删除！")
	//	return
	//}

	if rowsAffected := t.TsRty.DeleteById(int64(pathId));rowsAffected != 1 {
		response.Fail(ctx, nil, "删除失败，请重试！")
		return
	}

	response.Success(ctx, nil, "删除成功！")
}

func (t TsController) List(ctx *gin.Context) {

	// 接收参数
	var voList vo.TsList
	if err := ctx.ShouldBind(&voList); err != nil {
		response.Fail(ctx, nil, "数据验证错误，请检查提交的内容！")
		return
	}

	results, total := t.TsRty.List(voList)

	response.Success(ctx, gin.H{"data":results, "total":total}, "查询列表成功。")
}

func NewTsController() ITsController{
	return  TsController{TsRty: respository.NewTsRepository()}
}